#include "LRUCache.h"
LRUCache::LRUCache(int capacity) : capacity{capacity}, size{0} {
    head = new DLinkedNode();
    tail = new DLinkedNode();
    head->next = tail;
    tail->prev = head;
};

int LRUCache::get(int key) {
    if (!cache.count(key))
        return -1;
    else {
        DLinkedNode *node = cache[key];
        moveToHead(node);
        return node->value;
    }
}
void LRUCache::put(int key, int value) {
    if (!cache.count(key)) {
        DLinkedNode *node = new DLinkedNode(key, value);
        cache[key] = node;
        addToHead(node);
        ++size;
        // 超过容量，找到最后一个节点删除，cache里面同样删除
        if (size > capacity) {
            DLinkedNode *removed = removeTail();
            cache.erase(removed->key);
            delete removed;
            --size;
        }
    } else {
        DLinkedNode *node = cache[key];
        node->value = value;
        moveToHead(node);
    }
}

// 将node指针插入链表头
void LRUCache::addToHead(DLinkedNode *node) {
    node->prev = head;
    node->next = head->next;
    head->next->prev = node;
    head->next = node;
}

// 删除node节点
void LRUCache::removeNode(DLinkedNode *node) {
    node->prev->next = node->next;
    node->next->prev = node->prev;
}

// 移除当前节点，将当前节点加入链表头
void LRUCache::moveToHead(DLinkedNode *node) {
    removeNode(node);
    addToHead(node);
}
// 移除尾节点
DLinkedNode *LRUCache::removeTail() {
    DLinkedNode *node = tail->prev;
    removeNode(node);
    return node;
}

LRUCache::~LRUCache() {
    delete head;
    delete tail;
    for (auto item : cache) {
        delete item.second;
    }
}
